<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人收藏</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css">

    <script src="../static/js/jquery.js"></script>
    <script src="../static/layui/js/layui.js"></script>

    <style>
        body {
            background-color: #f5f7fa;
            padding: 0;
            margin: 0;
            height: 100%;
            box-sizing: border-box;
        }
        /* 内容区域容器，控制左右间距 */
        .content-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        /* 整体白框包裹样式 */
        .white-box {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            position: relative; /* 用于定位右上角按钮 */
        }
        .current-path {
            font-size: 14px;
            color: #666;
            margin-bottom: 30px; /* 增加与下方收藏夹的间距 */
        }
        .current-path a {
            color: #6a11cb;
            text-decoration: none;
        }
        .current-path a:hover {
            text-decoration: underline;
        }
        .folder-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            justify-content: flex-start; /* 从左侧开始排列 */
        }
        .folder-item {
            width: calc((100% - 80px) / 5); /* 计算宽度，一行五个，间距20px，共4个间距 */
            min-width: 150px; /* 最小宽度，防止过窄 */
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 20px;
            text-align: center;
            background-color: #fff;
            cursor: pointer;
            transition: all 0.3s;
            box-sizing: border-box;
        }
        .folder-item:hover {
            box-shadow: 0 2px 8px rgba(106, 17, 203, 0.1);
            transform: translateY(-2px);
            border-color: rgba(106, 17, 203, 0.2);
        }
        .folder-icon {
            font-size: 48px; /* 增大图标 */
            color: #6a11cb;
            margin-bottom: 15px; /* 增加间距 */
        }
        .folder-name {
            font-size: 16px; /* 增大名称字体 */
            margin-bottom: 8px; /* 增加间距 */
            font-weight: 500;
            color: #333;
        }
        .folder-count {
            font-size: 14px; /* 增大数量字体 */
            color: #999;
        }
        .btn-new-folder {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            position: absolute;
            top: 25px;
            right: 25px;
            transition: all 0.3s;
        }
        .btn-new-folder:hover {
            background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
            transform: translateY(-2px);
        }
        /* 弹窗样式 */
        .layui-layer {
            border-radius: 8px !important;
            background-color: white !important;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1) !important;
        }
        .layui-layer-title {
            background-color: #f5f5f5 !important;
            border-bottom: 1px solid #e6e6e6 !important;
            font-size: 16px !important;
            font-weight: bold !important;
            color: #333 !important;
        }
        .layui-layer-content {
            padding: 20px !important;
        }

        .layui-layer.layui-layer-dialog.layui-layer-msg {
            color: #000; /* 修改为你想要的颜色，这里以黑色为例 */
        }

        .form-item {
            margin-bottom: 15px;
        }
        .form-item label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #333;
        }
        .form-item input {
            width: 100%;
            padding: 8px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            box-sizing: border-box;
            background-color: white;
            color: #333;
        }
        .form-item input::placeholder {
            color: #999;
        }
        .btn-group {
            text-align: right;
            margin-top: 20px;
        }
        .btn-group button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
            transition: all 0.3s;
        }
        .btn-create {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
        }
        .btn-create:hover {
            background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
        }
        .btn-cancel {
            background-color: #f5f5f5;
            color: #333;
            border: 1px solid #e6e6e6;
        }
        .btn-cancel:hover {
            background-color: #eeeeee;
        }

        /* 店铺容器整体样式 */
        .shops-container {
            margin-top: 20px;
        }

        /* 单个店铺卡片样式 */
        .shop-item {
            display: flex;
            align-items: center;
            padding: 12px;
            border: 1px solid #e5e5e5;
            border-radius: 6px;
            margin-bottom: 12px;
            background-color: #fff;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
            transition: box-shadow 0.3s ease;
        }

        /* 鼠标悬浮时卡片阴影变化，增强交互感 */
        .shop-item:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 店铺图片样式 */
        .shop-item img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            margin-right: 15px;
            border-radius: 4px;
        }

        /* 店铺信息容器样式：flex布局让收藏图标右对齐 */
        .shop-info {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        /* 店铺名称样式 */
        .shop-info .shop-name {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 6px;
            color: #333;
        }

        /* 店铺描述样式 */
        .shop-info .shop-desc {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
        }

        /* 路径节点样式：蓝色 + 下划线，hover 加深 */
        .path-node {
            color: #6a11cb;
            text-decoration: underline;
            cursor: pointer;
            margin: 0 4px;
        }
        .path-node:hover {
            color: #5a0dc8; /*  hover 时颜色加深 */
            text-decoration: none;
        }

        /* 收藏图标样式：默认显示已收藏状态，右对齐 */
        .shop-collect {
            position: relative; /* 避免脱离文档流导致遮挡 */
            width: 36px;
            height: 36px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            color: #999;
            margin-left: auto; /* 右对齐 */
        }

        /* 已收藏/hover时的样式：渐变背景+白色图标 */
        .shop-collect.active, .shop-collect:hover {
            background: linear-gradient(45deg, #ff5e62 0%, #ff9966 100%);
            color: white;
        }
    </style>
</head>
<body>
<div class="content-container">
    <div class="white-box">
        <div class="current-path">
            当前路径：<a class="path-node" data-level="0" data-folderid="0">默认收藏夹</a>
        </div>

        <div class="folder-container" id="folderContainer">
            <div class="folder-item" data-folder="default">
                <i class="layui-icon folder-icon layui-icon-file"></i>
                <div class="folder-name">默认收藏夹</div>
                <div class="folder-count">0个店铺</div>
            </div>
            <div class="folder-item" data-folder="book">
                <i class="layui-icon folder-icon layui-icon-read"></i>
                <div class="folder-name">二手书</div>
                <div class="folder-count">0个店铺</div>
            </div>
            <div class="folder-item" data-folder="food">
                <i class="layui-icon folder-icon layui-icon-app"></i>
                <div class="folder-name">美食</div>
                <div class="folder-count">3个店铺</div>
            </div>
            <div class="folder-item" data-folder="treasure">
                <i class="layui-icon folder-icon layui-icon-diamond"></i>
                <div class="folder-name">宝藏二手店铺</div>
                <div class="folder-count">0个店铺</div>
            </div>
            <div class="folder-item" data-folder="game">
                <i class="layui-icon folder-icon layui-icon-game"></i>
                <div class="folder-name">电玩</div>
                <div class="folder-count">0个店铺</div>
            </div>
        </div>
        <!-- 新增的收藏店铺容器：默认显示已收藏图标 -->
        <div class="shops-container" id="shopsContainer">
            <div class="shop-item">
                <img src="https://picsum.photos/200/200?random=1" alt="美味餐厅">
                <div class="shop-info">
                    <!-- 默认添加active类+实心星 -->
                    <div class="shop-collect active" onclick="toggleCollect(1, this)">
                        <i class="layui-icon layui-icon-star"></i>
                    </div>
                    <div class="shop-name">美味轩餐厅</div>
                    <div class="shop-desc">主打各类美食，环境优雅，服务周到</div>
                </div>
            </div>
            <div class="shop-item">
                <img src="https://picsum.photos/200/200?random=2" alt="二手书店">
                <div class="shop-info">
                    <div class="shop-collect active" onclick="toggleCollect(2, this)">
                        <i class="layui-icon layui-icon-star"></i>
                    </div>
                    <div class="shop-name">墨香二手书店</div>
                    <div class="shop-desc">海量二手书籍，价格实惠，种类丰富</div>
                </div>
            </div>
            <div class="shop-item">
                <img src="https://picsum.photos/200/200?random=3" alt="电玩店">
                <div class="shop-info">
                    <div class="shop-collect active" onclick="toggleCollect(3, this)">
                        <i class="layui-icon layui-icon-star"></i>
                    </div>
                    <div class="shop-name">电玩世界</div>
                    <div class="shop-desc">各类电玩设备、游戏周边，应有尽有</div>
                </div>
            </div>
        </div>
        <button class="btn-new-folder" id="btnNewFolder">新建收藏夹</button>
    </div>
</div>
<script src="../static/js/jquery.cookie.js"></script>
<script>
    // 用户名
    let username = $.cookie("username");
    // 用户id
    let u_id;
    // 当前收藏夹id
    let folderId = 0;
    // 当前收藏夹的父收藏夹id
    let currentFatherFolderId = 0;


    $(document).ready(function() {
        // username = "张三";
        getUserIdByName(username, function(userId) {
            if (userId) {
                u_id = userId;
                selectFavoriteShop();
                selectFavoritesList();
                // updateShopCountInFolder();
            } else {
                console.error("无法获取用户ID，无法继续操作");
                layer.msg("获取用户信息失败，请刷新页面重试");
            }
        });
    });


    layui.use(['layer'], function() {
        var layer = layui.layer;
        var folderIndex = null; // 新建收藏夹弹窗索引
        var iconLayerIndex = null; // 图标库弹窗索引

        // 新建收藏夹按钮点击事件
        document.getElementById('btnNewFolder').addEventListener('click', function() {
            // 创建弹窗并保存索引
            folderIndex = layer.open({
                type: 1,
                title: '新建收藏夹',
                content: `
            <div class="form-item">
                <label for="folderName">收藏夹名称</label>
                <input type="text" id="folderName" placeholder="请输入收藏夹名称">
            </div>
            <div class="form-item">
                <label for="folderIcon">收藏夹图标</label>

                <input type="hidden" id="selectedIcon" value="">

                <button type="button" id="chooseIconBtn" style="padding: 8px 15px; border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">
                    选择图标 <i class="layui-icon layui-icon-down"></i>
                </button>

                <div id="iconPreview" style="margin-top: 10px; display: none;">
                    <img id="previewImg" src="" alt="选中的图标" style="width: 40px; height: 40px;">
                </div>
            </div>
            <div class="btn-group">
                <button type="button" class="btn-cancel" data-action="cancel">取消</button>
                <button type="button" class="btn-create" data-action="create">创建</button>
            </div>
        `,
                area: ['450px', '300px'] // 增大弹窗高度以容纳图标预览
            });

            // 选择图标按钮点击事件（在弹窗创建后绑定）
            document.getElementById('chooseIconBtn').addEventListener('click', function() {
                iconLayerIndex = layer.open({
                    type: 1,
                    title: '选择图标',
                    content: `
                    <div style="padding: 20px; display: flex; flex-wrap: wrap; gap: 15px;">
                        <img src="/static/alibaba-icon/书店.svg" alt="图书" class="icon-option" data-icon="/static/alibaba-icon/书店.svg">
                        <img src="/static/alibaba-icon/美食.svg" alt="美食" class="icon-option" data-icon="/static/alibaba-icon/美食.svg">
                        <img src="/static/alibaba-icon/电玩.svg" alt="电玩" class="icon-option" data-icon="/static/alibaba-icon/电玩.svg">
                        <img src="/static/alibaba-icon/健身.svg" alt="健身" class="icon-option" data-icon="/static/alibaba-icon/健身.svg">
                        <img src="/static/alibaba-icon/二手设备.svg" alt="二手" class="icon-option" data-icon="/static/alibaba-icon/二手设备.svg">
                        <img src="/static/alibaba-icon/宠物.svg" alt="宠物" class="icon-option" data-icon="/static/alibaba-icon/宠物.svg">
                    </div>
                `,
                    area: ['500px', '320px']
                });
            });
        });

        // 图标选择和按钮事件处理
        document.addEventListener('click', function(e) {
            var target = e.target;

            // 点击图标库中的图标
            if (target.classList.contains('icon-option')) {
                const iconPath = target.dataset.icon;
                // 存入隐藏输入框
                document.getElementById('selectedIcon').value = iconPath;
                // 显示预览
                const previewImg = document.getElementById('previewImg');
                previewImg.src = iconPath;
                document.getElementById('iconPreview').style.display = 'block';
                // 关闭图标库弹窗
                layer.close(iconLayerIndex);
            }

            // 取消按钮
            if (target.dataset.action === 'cancel') {
                layer.close(folderIndex);
            }

            // 创建按钮
            if (target.dataset.action === 'create') {
                const folderName = document.getElementById('folderName').value.trim();
                const icon = document.getElementById('selectedIcon').value;

                // 验证输入
                if (!folderName) {
                    layer.msg('请输入收藏夹名称');
                    return;
                }
                if (!icon) {
                    layer.msg('请选择收藏夹图标');
                    return;
                }

                // 调用创建收藏夹函数
                createNewFolder(folderName, icon, currentFatherFolderId);

                // 关闭弹窗并提示
                layer.close(folderIndex);
                layer.msg('收藏夹【' + folderName + '】创建成功');
            }
        });
    });



    function getUserIdByName(username, callback) {
        $.ajax({
            url: "/personalCollection/getUserIdByName",
            type: "post",
            data: {
                username: username
            },
            dataType: "json",
            success: function (res) {
                if (res.code === 200) {
                    const userId = res.data;
                    console.log("获取到的用户 ID：", userId);
                    // 调用回调函数传递获取到的userId
                    callback(userId);
                } else {
                    console.error("获取用户 ID 失败，错误信息：", res.msg);
                    callback(null);
                }
            },
            error: function (xhr, status, error) {
                console.error("Ajax 请求失败，状态：" + status + "，错误：" + error);
                callback(null);
            }
        });
    }

    // function updateShopCountInFolder(){
    //     $.ajax({
    //         url:"/personalCollection/updateShopCountInFolder",
    //         type:"post",
    //         dataType:"json",
    //         data:{
    //             userId:u_id,
    //             fatherId:folderId
    //         },
    //         success: function (res){
    //             console.log("更新店铺数量后的文件夹：", res);
    //         },
    //         error: function (){
    //             alert("更新文件夹内的店铺数量出错...")
    //         }
    //     })
    // }

    function selectFavoriteShop(){
        // 确保u_id存在
        if (!u_id) {
            console.error("u_id为空，无法获取收藏店铺列表");
            layer.msg("用户信息异常，请重试");
            return;
        }

        $.ajax({
            url: "/personalCollection/selectFavoriteShop",
            type: "post",
            data: {
                u_id: u_id,
                folderId : folderId
            },
            dataType: "json",
            success: function (result) {
                if (result.code === 200) {
                    console.log("当前文件夹店铺：", result)
                    var shopsContainer = $("#shopsContainer");
                    shopsContainer.empty();

                    var shopList = result.data;
                    if (shopList && shopList.length > 0) {
                        for (var i = 0; i < shopList.length; i++) {
                            var shop = shopList[i];
                            // 拼接店铺 HTML：强制显示已收藏状态（active+实心星）
                            var shopHtml = `
                            <div class="shop-item">
                                <img src="${shop.avatarUrl}" alt="${shop.name}">
                                <div class="shop-info">
                                    <div class="shop-collect active" onclick="toggleCollect(${shop.id}, this)">
                                        <i class="layui-icon layui-icon-star"></i>
                                    </div>
                                    <div class="shop-name">${shop.name}</div>
                                    <div class="shop-desc">${shop.desc}</div>
                                </div>
                            </div>
                        `;
                            shopsContainer.append(shopHtml);
                        }
                    } else {
                        shopsContainer.html("<div style='text-align: center; padding: 20px; color: #999;'>收藏夹暂无店铺</div>");
                    }
                } else {
                    console.error("获取收藏店铺列表失败，错误信息：", result.msg);
                    layer.msg("获取收藏店铺列表失败");
                }
            },
            error: function (xhr, status, error) {
                console.log("u_id: " + u_id)
                console.log("folderId: " + folderId)
                console.error("Ajax 请求失败，状态：" + status + "，错误：" + error);
                layer.msg("请求失败，请重试");
            }
        });
    }

    function selectFavoritesList(){
        // 确保u_id存在
        if (!u_id) {
            console.error("u_id为空，无法获取收藏列表");
            layer.msg("用户信息异常，请重试");
            return;
        }

        $.ajax({
            url: "/personalCollection/selectFavoritesList",
            type: "post",
            data: {
                u_id: u_id,  // 明确指定参数名，避免歧义
                fatherFolderId:currentFatherFolderId,
            },
            dataType: "json",
            success: function (result) {
                console.log("文件夹：", result)
                console.log("currentFatherFolderId:", currentFatherFolderId)
                if (result.code === 200) {
                    var folderContainer = $("#folderContainer");
                    folderContainer.empty();

                    var favoritesList = result.data;
                    if (favoritesList && favoritesList.length > 0) {
                        for (var i = 0; i < favoritesList.length; i++) {
                            var folder = favoritesList[i];
                            // 拼接收藏夹 HTML
                            var folderHtml = `
                                    <div class="folder-item" data-folder="${folder.id}">
                                        <img src="${folder.icon}" alt="${folder.folderName}" class="folder-icon"/>
                                        <div class="folder-name">${folder.folderName}</div>
                                        <div class="folder-count">${folder.shopCount}个店铺</div>
                                    </div>
                                `;
                            folderContainer.append(folderHtml);
                        }
                    } else {
                        folderContainer.html("<div style='text-align: center; padding: 20px; color: #999;'>暂无收藏夹</div>");
                    }
                } else {
                    console.error("获取收藏夹列表失败，错误信息：", result.msg);
                    layer.msg("获取收藏夹列表失败");
                }
            },
            error: function (xhr, status, error) {
                console.log("userId: "+u_id);
                console.log("currentFatherFolderId: " + currentFatherFolderId)
                console.error("Ajax 请求失败，状态：" + status + "，错误：" + error);
                layer.msg("请求失败，请重试");
            }
        });
    }


    // 新增收藏夹
    function createNewFolder(folderName,icon,currentFatherFolderId) {
        // 实际应用中应该发送AJAX请求到后端保存
        $.ajax({
            url: "/personalCollection/createFolder",
            type: "post",
            data: {
                uId: u_id,
                folderName: folderName,
                icon:icon,
                father_folder_id:currentFatherFolderId
            },
            dataType: "json",
            success: function(res) {
                if (res.code === 200) {
                    // 创建成功后刷新列表
                    selectFavoriteShop();
                    selectFavoritesList();
                } else {
                    layer.msg("创建失败：" + res.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error("创建收藏夹失败：", error);
                layer.msg("创建收藏夹失败，请重试");
            }
        });
    }

    // 点击收藏夹在当前路径上进行显示
    /**
     * 追加路径节点（点击文件夹卡片时调用）
     * @param {string} folderName - 要追加的文件夹名称
     * @param folderId
     */
    function appendPathNode(folderName,folderId) {
        // 获取当前最后一个路径节点的层级，计算新节点的层级
        const lastLevel = parseInt($(".path-node:last").data("level"));
        const newLevel = lastLevel + 1;

        // 追加“斜杠 + 新路径节点”（新节点带层级标识）
        $(".current-path").append(`<span class="divide-node">/</span>
                                        <a class="path-node" data-level="${newLevel}" data-folderid="${folderId}">${folderName}</a>
                                        `);
    }

    /**
     * 重置路径节点（点击路径节点时调用）
     * @param {jQuery} clickedNode - 被点击的路径节点（jQuery 对象）
     */
    function resetPathToNode(clickedNode) {
        // 获取被点击节点的层级
        const targetLevel = parseInt(clickedNode.data("level"));

        // 遍历所有路径节点，删除层级大于 targetLevel 的节点及其前面的斜杠
        $(".path-node").each(function() {
            const nodeLevel = parseInt($(this).data("level"));
            if (nodeLevel > targetLevel) {
                // 先删除节点前面的斜杠（通过 prev() 找到前一个元素，即斜杠）
                $(this).prev().remove();
                // 再删除当前节点
                $(this).remove();
            }
        });
    }

    // 点击“文件夹卡片”：追加路径节点
    $(document).on("click", ".folder-item", function() {
        const folderName = $(this).find(".folder-name").text();
        folderId = $(this).data("folder");
        appendPathNode(folderName,folderId);

        selectFavoriteShop();

        currentFatherFolderId = folderId;
        selectFavoritesList();
    });

    // 点击“路径节点”：重置路径到当前节点（只删除下级）
    $(document).on("click", ".path-node", function() {
        resetPathToNode($(this));
        folderId = $(this).data("folderid");
        selectFavoriteShop();

        currentFatherFolderId = folderId;
        selectFavoritesList();
    });


    // // 取消收藏功能：仅保留取消逻辑，点击直接弹确认窗
    // window.toggleCollect = function(shopId, element) {
    //     // 提取店铺信息（用于弹窗和提示文案）
    //     const shopItem = element.closest('.shop-item');
    //     const shopName = shopItem.querySelector('.shop-name').textContent.trim();
    //     const icon = element.querySelector('i');
    //
    //     // 直接弹出取消收藏确认窗（无需判断是否已收藏，页面显示的均为已收藏）
    //     layui.use('layer', function() {
    //         const layer = layui.layer;
    //         layer.confirm(
    //             `确定要取消收藏【${shopName}】吗？`,
    //             {
    //                 title: '取消收藏确认',
    //                 btn: ['确定取消', '取消'], // 两个按钮
    //                 btnAlign: 'c', // 按钮居中
    //                 icon: 3 // 警告图标
    //             },
    //             // 点击“确定取消”回调
    //             function(index) {
    //                 // 1. 关闭弹窗
    //                 layer.close(index);
    //                 // 2. 视觉反馈：切换为未收藏样式（空心星+移除active）
    //                 icon.className = 'layui-icon layui-icon-star-o';
    //                 element.classList.remove('active');
    //                 // 3. 轻提示
    //                 showToast(`已取消收藏【${shopName}】`);
    //                 // 4. 同步后端取消状态（isCollected固定为false）
    //                 syncCollectToBackend(shopId, false, element, icon);
    //             },
    //             // 点击“取消”回调（仅关闭弹窗，不操作）
    //             function(index) {
    //                 layer.close(index);
    //             }
    //         );
    //     });
    // };
    //
    // // 封装：同步取消收藏状态到后端
    // function syncCollectToBackend(shopId, isCollected, element, icon) {
    //     const shopName = element.closest('.shop-item').querySelector('.shop-name').textContent.trim();
    //
    //     $.ajax({
    //         url: '/personalCollection/deleteFavoriteShop', // 替换为你的实际后端接口
    //         type: 'post',
    //         data: {
    //             shopId: shopId,
    //             isCollected: isCollected, // 固定为false（取消收藏）
    //             u_id: u_id,
    //             folderId: folderId
    //         },
    //         dataType: 'json',
    //         success: function(res) {
    //             console.log(shopId);
    //             console.log(isCollected);
    //             console.log(u_id);
    //             console.log(folderId);
    //
    //             if (res.code !== 200) {
    //                 icon.className = 'layui-icon layui-icon-star';
    //                 element.classList.add('active');
    //                 showToast(`取消收藏失败：${res.msg || '服务器异常'}`);
    //             }
    //         },
    //         error: function() {
    //             console.log(shopId);
    //             console.log(isCollected);
    //             console.log(u_id);
    //             console.log(folderId);
    //             // 网络错误 → 回滚状态
    //             icon.className = 'layui-icon layui-icon-star';
    //             element.classList.add('active');
    //             showToast('网络异常，取消收藏失败');
    //         }
    //     });
    // }
    //
    // // 轻提示功能（操作结果反馈）
    // function showToast(message) {
    //     const toast = document.createElement('div');
    //     toast.className = 'layui-layer layui-layer-dialog layui-layer-msg';
    //     toast.style.cssText = `
    //             position: fixed;
    //             top: 50%;
    //             left: 50%;
    //             transform: translate(-50%, -50%);
    //             padding: 10px 20px;
    //             background: rgba(106, 17, 203, 0.8);
    //             color: white;
    //             border-radius: 4px;
    //             z-index: 9999;
    //             opacity: 0;
    //             transition: opacity 0.3s;
    //         `;
    //     toast.textContent = message;
    //     document.body.appendChild(toast);
    //
    //     // 淡入
    //     setTimeout(() => {
    //         toast.style.opacity = '1';
    //     }, 10);
    //
    //     // 2秒后淡出并移除
    //     setTimeout(() => {
    //         toast.style.opacity = '0';
    //         setTimeout(() => {
    //             document.body.removeChild(toast);
    //         }, 300);
    //     }, 2000);
    // }


    // 收藏/取消收藏功能：双向切换（取消→收藏→取消...）
    window.toggleCollect = function(shopId, element) {
        const shopItem = element.closest('.shop-item');
        const shopName = shopItem.querySelector('.shop-name').textContent.trim();
        const icon = element.querySelector('i');
        // 判断当前是否已收藏（通过图标类名）
        const isCurrentlyCollected = icon.classList.contains('layui-icon-star');

        if (isCurrentlyCollected) {
            // 情况1：已收藏 → 弹框取消
            layui.use('layer', function() {
                const layer = layui.layer;
                layer.confirm(
                    `确定要取消收藏【${shopName}】吗？`,
                    {
                        title: '取消收藏确认',
                        btn: ['确定取消', '取消'],
                        btnAlign: 'c',
                        icon: 3
                    },
                    function(index) {
                        layer.close(index);
                        // 视觉反馈：切换为未收藏
                        icon.className = 'layui-icon layui-icon-star-o';
                        element.classList.remove('active');
                        showToast(`已取消收藏【${shopName}】`);
                        // 同步后端：取消收藏（isCollected: false）
                        syncCollectToBackend(shopId, false, element, icon);
                    },
                    function(index) {
                        layer.close(index);
                    }
                );
            });
        } else {
            // 情况2：未收藏 → 直接收藏
            icon.className = 'layui-icon layui-icon-star';
            element.classList.add('active');
            showToast(`已收藏【${shopName}】`);
            // 同步后端：收藏（isCollected: true）
            syncCollectToBackend(shopId, true, element, icon);
        }
    };

    // 封装：同步收藏/取消状态到后端
    function syncCollectToBackend(shopId, isCollected, element, icon) {
        const shopName = element.closest('.shop-item').querySelector('.shop-name').textContent.trim();

        $.ajax({
            // 替换为实际后端接口（需同时支持“收藏”和“取消收藏”）
            url: '/personalCollection/toggleFavoriteShop',
            type: 'post',
            data: {
                shopId: shopId,
                isCollected: isCollected, // true=收藏，false=取消
                u_id: u_id,
                folderId: folderId
            },
            dataType: 'json',
            success: function(res) {
                console.log("参数：", shopId, isCollected, u_id, folderId);
                if (res.code !== 200) {
                    // 后端失败 → 回滚前端状态
                    const rollbackState = !isCollected;
                    icon.className = rollbackState
                        ? 'layui-icon layui-icon-star'
                        : 'layui-icon layui-icon-star-o';
                    element.classList.toggle('active', rollbackState);
                    showToast(`${isCollected ? '收藏' : '取消收藏'}失败：${res.msg || '服务器异常'}`);
                }
            },
            error: function() {
                console.log("参数：", shopId, isCollected, u_id, folderId);
    // 网络        // 网络错误 → 回滚前端状态
                const rollbackState = !isCollected;
                icon.className = rollbackState
                    ? 'layui-icon layui-icon-star'
                    : 'layui-icon layui-icon-star-o';
                element.classList.toggle('active', rollbackState);
                showToast(`网络异常，${isCollected ? '收藏' : '取消收藏'}失败`);
            }
        });
    }

    // 轻提示功能（操作结果反馈）
    function showToast(message) {
        const toast = document.createElement('div');
        toast.className = 'layui-layer layui-layer-dialog layui-layer-msg';
        toast.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 10px 20px;
            background: rgba(106, 17, 203, 0.8);
            color: white;
            border-radius: 4px;
            z-index: 9999;
            opacity: 0;
            transition: opacity 0.3s;
        `;
        toast.textContent = message;
        document.body.appendChild(toast);

        // 淡入
        setTimeout(() => {
            toast.style.opacity = '1';
        }, 10);

        // 2秒后淡出并移除
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 2000);
    }
</script>

</body>
</html>